﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using AsyncLibrary;
using AsyncLibrary.StatusListener;
using AsyncLibrary.UI;
using log4net.Config;

namespace AsycnLibraryTest
{
  public partial class AsynLibraryTestForm : Form
  {
    private VirtualThread _thread;
    private UpdateItemsOperation _op;
    private ListBox _lb;
    private List<string> _items;

    public AsynLibraryTestForm()
    {
      InitializeComponent();
      Init();
    }

    private void Init()
    {
      XmlConfigurator.Configure();

      _thread = new VirtualThread("Upate Operations Thread");
      _items = new List<string>();
      for (var i = 1; i < 12; i++)
        _items.Add(string.Format("op{0}", i));

      _op = new UpdateItemsOperation(_items);
      _op.OnError += OperationError;

      _lb = new ListBox();
      loadingControl.Init(_lb, _op);
      loadingControl.Loaded += LoadingControlOnLoaded;
    }

    private void LoadingControlOnLoaded()
    {
      _lb.Items.Clear();
      _lb.Items.AddRange(_items.ToArray());
    }

    private void OperationError(string s)
    {
      MessageBox.Show(this, s, @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    private void StatusFormButtonClick(object sender, EventArgs e)
    {
      _op.StatusListeners.Set(new StatusFormDecorator(this, new StatusForm(), _op));
      _thread.QueueOperation(_op);
    }

    private void ProgressBarButtonClick(object sender, EventArgs e)
    {
      var progressBarListener = new ProgressBarListener(progressBarTest);
      _op.StatusListeners.Set(new ControlDecoratorBase(progressBarListener, _op));
      _thread.QueueOperation(_op);
    }

    private void LabelButtonClick(object sender, EventArgs e)
    {
      var labelListener = new LabelListener(labelTest);
      _op.StatusListeners.Set(new ControlDecoratorBase(labelListener, _op));
      _thread.QueueOperation(_op);
    }

    private void BothButtonClick(object sender, EventArgs e)
    {
      var progressBarListener = new ProgressBarListener(progressBarTest);
      var labelListener = new LabelListener(labelTest);
      _op.StatusListeners.Clear();
      _op.StatusListeners.Add(new ControlDecoratorBase(progressBarListener, _op));
      _op.StatusListeners.Add(new ControlDecoratorBase(labelListener, _op));
      _thread.QueueOperation(_op);
    }

    private void PopulateListboxButtonClick(object sender, EventArgs e)
    {
      _op.LoadingListener = loadingControl;
      loadingControl.LoadData();
    }

  }

}
